//
// Created by denglibin on 2021/4/8.
//

#include "LoadModelWindow.h"

LoadModelWindow::LoadModelWindow(int width, int height, std::string &title): Window(width, height, title){
    string vertexPath = R"(D:\CLionProjects\opengl-mingw\shader4\nanosuit.vs)";
    string fragmentPath = R"(D:\CLionProjects\opengl-mingw\shader4\nanosuit.fs)";
    shader = new Shader(vertexPath, fragmentPath);
    loadModel();
}
LoadModelWindow::~LoadModelWindow(){
    delete model;
    delete shader;
}
void LoadModelWindow::paint(){
    //设置清除颜色
    glClearColor(0, 0, 0, 1.0f);
    //使用上面设置的颜色清空屏幕
    // glClear(GL_COLOR_BUFFER_BIT);
    //因为使用了深度测试，我们也想要在每次渲染迭代之前清除深度缓冲（否则前一帧的深度信息仍然保存在缓冲中）。就像清除颜色缓冲一样
    glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);

    shader->use();
    modelMat();
    viewMat();
    projectionMat();
    model->Draw(*shader);

}
void LoadModelWindow::loadModel() {
    std::string path = R"(D:\CLionProjects\opengl-mingw\resources\model\nanosuit\nanosuit.obj)";
    model = new Model(path.c_str());

}
void LoadModelWindow::modelMat(){
    glm::mat4 model = glm::mat4(1.0f);
    model = glm::translate(model, glm::vec3(0, -2.0f, -5.0f));
    model = glm::scale(model, glm::vec3(0.3f, 0.3f, 0.3f));
    shader->setMatrix4fv("model", model);
}

void LoadModelWindow::viewMat(){
    //摄像机位置 + 摄像机方向 = 目标位置
    //LookAt函数需要一个位置、目标和上向量
    glm::mat4 view  = glm::lookAt(camera->cameraPos,
                                  camera->cameraPos + camera->cameraFront,
                                  camera->cameraUp);

    shader->setMatrix4fv("view", view);
}
void LoadModelWindow::projectionMat(){
    glm::mat4 proj = glm::perspective(glm::radians(camera->fovY), (float)width/(float)height, 0.1f, 100.0f);
    shader->setMatrix4fv("projection", proj);
}